import { isPercentage, isSafeNumeric } from 'src/utils/utils'
// eslint-disable-next-line no-undef
const { SSF, utils, writeFile } = XLSX

const CELLSTYLE = {
  font: { name: 'fangsong', sz: 16 }, alignment: { horizontal: 'center', vertical: 'center', wrapText: true }
}

const sheetFromArrayOfArrays = data => {
  const ws = {}
  const range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } }
  for (let R = 0; R !== data.length; ++R) {
    for (let C = 0; C !== data[R].length; ++C) {
      if (range.s.r > R) range.s.r = R
      if (range.s.c > C) range.s.c = C
      if (range.e.r < R) range.e.r = R
      if (range.e.c < C) range.e.c = C
      const cell = { v: data[R][C] ?? '' }, cellRef = utils.encode_cell({ c: C, r: R })
      if (isSafeNumeric(cell.v)) {
        cell.t = 'n'
        cell.z = SSF._table[0]
      } else if (isPercentage(cell.v)) {
        cell.t = 'n'
        cell.z = SSF._table[10]
        cell.v = Number(String(cell.v).replace('%', '')) / 100
      } else if (typeof cell.v === 'boolean') cell.t = 'b'
      else {
        cell.t = 's'
        cell.z = SSF._table[0]
      }
      cell.s = CELLSTYLE
      ws[cellRef] = cell
    }
  }
  if (range.s.c < 10000000) ws['!ref'] = utils.encode_range(range)
  return ws
}

export function exportJsonToExcel ({
  multiHeader = [], header = [], data = [], fileName = 'excel-list', merges = [],
  printHeader = [[1, 1]], autoWidth = false, bookType = 'xlsx', cols = [], sheetName
} = {}) {
  /* original data */
  data = [...data]

  for (let i = 0; i < header.length; i++) data[i].unshift(header[i])
  for (let i = 0; i < multiHeader.length; i++) {
    if (!multiHeader[i]) continue
    for (let j = multiHeader[i].length - 1; j > -1; j--) data[i].unshift(multiHeader[i][j])
  }
  const ws = [], wsName = sheetName
  for (let j = 0; j < header.length; j++) ws.push(sheetFromArrayOfArrays(data[j]))

  if (autoWidth) {
    /* 设置worksheet每列的最大宽度 */
    const colWidth = []
    for (let k = 0; k < header.length; k++) {
      colWidth.push(
        data[k].map(row =>
          row.map(val => {
            /* 先判断是否为空 */
            if (!val) return { wch: 10 }
            /* 再判断是否为中文 */
            else if (val.toString().charCodeAt(0) > 255) return { wch: 5 }
            else return { wch: 5 }
          })
        )
      )
    }

    /* 以第一行为初始值 */
    const result = []
    for (let k = 0; k < colWidth.length; k++) {
      result[k] = colWidth[k][0]
      for (let i = 1; i < colWidth[k].length; i++) {
        for (let j = 0; j < colWidth[k][i].length; j++) {
          if (result[k][j].wch < colWidth[k][i][j].wch) result[k][j].wch = colWidth[k][i][j].wch
        }
      }
    }
    // 分别给sheet表设置宽度
    for (let l = 0; l < result.length; l++) ws[l]['!cols'] = result[l]
  }

  const workbook = utils.book_new()
  /* add worksheet to workbook */
  for (let k = 0; k < header.length; k++) {
    if (!autoWidth) {
      ws[k]['!cols'] = []
      for (let i = 0; i < header[k].length; i++) ws[k]['!cols'].push({ wch: (cols && cols[k] && cols[k][i]) || 20 })
    }
    if (merges[k] && merges[k].length) {
      if (!ws[k]['!merges']) ws[k]['!merges'] = []
      merges[k].forEach(item => ws[k]['!merges'].push(utils.decode_range(item)))
    }
    ws[k]['!printHeader'] = printHeader[k]
    ws[k]['!pageSetup'] = { scale: 'auto', orientation: 'landscape' }
    utils.book_append_sheet(workbook, ws[k], wsName[k])
  }
  writeFile(workbook, `${fileName}.${bookType}`, {
    bookType, bookSST: false, type: 'binary', defaultCellStyle: CELLSTYLE
  })
}